package yyds.sniarbtej.transformer;

import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.*;
import yyds.sniarbtej.utils.DebugUtil;

public final class RemoveAgentVMArgs extends BaseClassTransformer {
    public String canTransformClassName() {
        return "sun/management/VMManagementImpl";
    }

    public byte[] rewrite(byte[] in) {
        return transform(in, new ClassRewriter() {
            @Override
            public void rewriteMethod(MethodNode node) {
                if ("getVmArguments".equals(node.name) && "()Ljava/util/List;".equals(node.desc)) {
                    InsnList insn = new InsnList();
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    insn.add(new FieldInsnNode(Opcodes.GETFIELD, "sun/management/VMManagementImpl", "vmArgs", "Ljava/util/List;"));
                    insn.add(new MethodInsnNode(Opcodes.INVOKESTATIC, methodOverride, "C1", "(Ljava/util/List;)Ljava/util/List;", false));
                    insn.add(new FieldInsnNode(Opcodes.PUTFIELD, "sun/management/VMManagementImpl", "vmArgs", "Ljava/util/List;"));
                    insn.add(new VarInsnNode(Opcodes.ALOAD, 0));
                    insn.add(new FieldInsnNode(Opcodes.GETFIELD, "sun/management/VMManagementImpl", "vmArgs", "Ljava/util/List;"));

                    for (AbstractInsnNode insnNode : node.instructions) {
                        if (insnNode.getType() == AbstractInsnNode.INSN && insnNode.getOpcode() == Opcodes.ARETURN) {
                            AbstractInsnNode beforeReturn = insnNode.getPrevious();
                            node.instructions.insert(beforeReturn, insn);
                            return;
                        }
                    }
                }
            }
        });
    }
}
